package com.swak.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.swak.utils.JDBCDrivers;
import com.swak.utils.StringUtils;

public class CreateDb {

	public static void main(String[] args) {
		Connection connection = null;
		try {
			String url = "jdbc:mysql://192.168.137.100:3308";
			String username = "root";
			String password = "rootadmin";
			Class.forName(JDBCDrivers.getDriverClassName(url));
			connection = DriverManager.getConnection(url, username, password);
			initDatabase(connection);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				connection.close();
			} catch (Exception e2) {
			}
		}
	}

	private static void initDatabase(Connection conn) {
		try {
			String dbname = "test_102";
			String sql = StringUtils.format(
					"create database if not exists %s default character set utf8 COLLATE utf8_general_ci", dbname);
			executeSql(conn, sql);
		} catch (Exception e) {
		}
	}

	protected static void executeSql(Connection connection, final String sql) {
		PreparedStatement ps = null;
		try {
			connection.setAutoCommit(false);
			ps = connection.prepareStatement(sql);
			ps.executeUpdate();
			connection.commit();
		} catch (SQLException e) {
			try {
				connection.rollback();
			} catch (SQLException ex) {
			}
		} finally {
			try {
				ps.close();
			} catch (Exception e2) {
			}
		}
	}

}
